package com.alipay.rebate.shop.configuration.shiro.realm;

import com.alipay.rebate.shop.configuration.shiro.token.PhoneToken;
import com.alipay.rebate.shop.constants.StatusCode;
import com.alipay.rebate.shop.constants.UserContant;
import com.alipay.rebate.shop.exceptoin.BusinessException;
import com.alipay.rebate.shop.pojo.user.customer.UserDto;
import com.alipay.rebate.shop.service.customer.CustomerUserService;
import com.alipay.rebate.shop.utils.EncryptUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PhoneShiroRealm extends AuthorizingRealm {

	private final Logger logger = LoggerFactory.getLogger(PhoneShiroRealm.class);

	private CustomerUserService userService;
	
	public PhoneShiroRealm(CustomerUserService userService) {
		this.userService = userService;
		this.setCredentialsMatcher(new HashedCredentialsMatcher(Sha256Hash.ALGORITHM_NAME));
	}
	
	@Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof PhoneToken;
    }
	
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		logger.debug("Get into DbShiroRealm");
		PhoneToken phoneToken = (PhoneToken)token;
		logger.debug("PhoneToken is :{}",phoneToken);
		String phone = phoneToken.getPhone();
		logger.debug("phone is :{}",phone);
		String mobileCode = phoneToken.getMobileCode();
		logger.debug("mobileCode is: {}",mobileCode);
		UserDto user = userService.getUserDtoInfoForPhoneLogin(phone);
		logger.debug("UserDto is :{}",user);
		if(user == null ){
			logger.debug("账号不存在");
			throw new UnknownAccountException();
		}
		if(UserContant.USER_STATUS_LOGOFF.equals(user.getUserStatus())){
			throw new BusinessException("账号不存在", StatusCode.INTERNAL_ERROR);
		}
		return new SimpleAuthenticationInfo(user, user.getEncryptPwd(), ByteSource.Util.bytes(
				EncryptUtil.encryptSalt), "dbRealm");
	}


	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
			return null;
	}

	
}
